//
//  UIImage+ZLCategory.m
//  ZLCategory
//
//  Created by zhaozl on 2022/4/26.
//

#import "UIImage+ZLCategory.h"

@implementation UIImage (ZLCategory)

/// 创建二维码图片
+ (UIImage *)zl_createQRImageWithContent:(NSString *)content {
    NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    CIImage *outputImage = filter.outputImage;
    CGFloat scale = 500 / CGRectGetWidth(outputImage.extent);
    CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
    CIImage *transformImage = [outputImage imageByApplyingTransform:transform];
    UIImage *qrcodeImage = [UIImage imageWithCIImage:transformImage];
    return qrcodeImage;
}

+ (UIImage *)zl_imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)zl_autoSize {
    return [self stretchableImageWithLeftCapWidth:self.size.width / 2.0 topCapHeight:self.size.height / 2.0];
}

- (UIImage *)zl_stretchInRect:(CGRect)rect {
    return [self zl_stretchInRect:rect mode:UIImageResizingModeStretch];
}

- (UIImage *)zl_stretchInRect:(CGRect)rect mode:(UIImageResizingMode)mode {
    UIEdgeInsets insets = UIEdgeInsetsMake(rect.origin.y, rect.origin.x, self.size.height - CGRectGetMaxY(rect), self.size.width - CGRectGetMaxX(rect));
    return [self resizableImageWithCapInsets:insets resizingMode:mode];
}

- (UIImage *)zl_resetColor:(UIColor *)color {
     UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
     CGContextRef context = UIGraphicsGetCurrentContext();
     CGContextTranslateCTM(context, 0, self.size.height);
     CGContextScaleCTM(context, 1.0, -1.0);
     CGContextSetBlendMode(context, kCGBlendModeNormal);
     CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
     CGContextClipToMask(context, rect, self.CGImage);
     [color setFill];
     CGContextFillRect(context, rect);
     UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return newImage;
}

- (UIImage *)zl_compressToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *compressedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return compressedImage;
}

@end
